document.addEventListener('DOMContentLoaded', function() {
    // DOM元素引用
    const totalUsersEl = document.getElementById('totalUsers');
    const companyUsersEl = document.getElementById('companyUsers');
    const jobSeekerUsersEl = document.getElementById('jobSeekerUsers');
    const activeJobsEl = document.getElementById('activeJobs');
    const totalResumesEl = document.getElementById('totalResumes');
    const totalApplicationsEl = document.getElementById('totalApplications');
    const pendingCompaniesEl = document.getElementById('pendingCompanies');
    const interviewApplicationsEl = document.getElementById('interviewApplications');
    const dateRangeSelect = document.getElementById('dateRangeSelect');
    const logoutBtn = document.getElementById('logoutBtn');

    // 图表实例
    let trendsChart = null;
    let applicationStatusChart = null;
    let industryChart = null;
    let salaryChart = null;

    // 初始化图表
    function initCharts() {
        // 趋势图表
        const trendsCtx = document.getElementById('trendsChart').getContext('2d');
        trendsChart = new Chart(trendsCtx, {
            type: 'line',
            data: {
                labels: [],
                datasets: [
                    {
                        label: '新增用户',
                        borderColor: '#4e79a7',
                        backgroundColor: 'rgba(78, 121, 167, 0.1)',
                        tension: 0.4,
                        fill: true
                    },
                    {
                        label: '新增职位',
                        borderColor: '#f28e2c',
                        backgroundColor: 'rgba(242, 142, 44, 0.1)',
                        tension: 0.4,
                        fill: true
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top',
                    }
                }
            }
        });

        // 申请状态图表
        const applicationStatusCtx = document.getElementById('applicationStatusChart').getContext('2d');
        applicationStatusChart = new Chart(applicationStatusCtx, {
            type: 'doughnut',
            data: {
                labels: ['待处理', '面试邀请', '已录用', '已拒绝'],
                datasets: [{
                    data: [0, 0, 0, 0],
                    backgroundColor: ['#ffc107', '#2196f3', '#4caf50', '#f44336'],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom'
                    }
                },
                cutout: '65%'
            }
        });

        // 行业分布图表
        const industryCtx = document.getElementById('industryChart').getContext('2d');
        industryChart = new Chart(industryCtx, {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '职位数量',
                    data: [],
                    backgroundColor: '#7b68ee',
                    borderRadius: 5
                },
                {
                    label: '企业数量',
                    data: [],
                    backgroundColor: '#26a69a',
                    borderRadius: 5
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            display: false
                        }
                    }
                },
                plugins: {
                    legend: {
                        position: 'top'
                    }
                }
            }
        });

        // 薪资范围图表
        const salaryCtx = document.getElementById('salaryChart').getContext('2d');
        salaryChart = new Chart(salaryCtx, {
            type: 'bar',
            data: {
                labels: [],
                datasets: [{
                    label: '职位数量',
                    data: [],
                    backgroundColor: '#26a69a',
                    borderRadius: 5
                }]
            },
            options: {
                indexAxis: 'y',
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    x: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    y: {
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });
    }

    // 获取系统概览数据
    async function loadSystemOverview() {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('http://localhost:3001/api/stats', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) throw new Error('获取数据失败');

            const data = await response.json();
            if (data.success) {
                // 更新概览卡片数据
                totalUsersEl.textContent = data.data.users.total;
                companyUsersEl.textContent = data.data.companies.total;
                jobSeekerUsersEl.textContent = data.data.users.jobSeeker;
                activeJobsEl.textContent = data.data.jobs.active;
                totalResumesEl.textContent = data.data.resumes.total;
                totalApplicationsEl.textContent = data.data.applications.total;
                pendingCompaniesEl.textContent = data.data.companies.pending;
                interviewApplicationsEl.textContent = data.data.applications.interview;

                // 更新申请状态图表
                applicationStatusChart.data.datasets[0].data = [
                    data.data.applications.pending,
                    data.data.applications.interview,
                    data.data.applications.accepted,
                    data.data.applications.rejected
                ];
                applicationStatusChart.update();
            }
        } catch (error) {
            console.error('加载系统概览数据失败:', error);
            alert('加载数据失败，请刷新页面重试');
        }
    }

    // 获取趋势数据
    async function loadTrendData(days = 30) {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch(`http://localhost:3001/api/stats/trends?days=${days}`, {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) throw new Error('获取趋势数据失败');

            const data = await response.json();
            if (data.success) {
                // 提取日期标签
                const labels = data.data.userTrends.map(item => item.date);

                // 更新趋势图表
                trendsChart.data.labels = labels;
                trendsChart.data.datasets[0].data = data.data.userTrends.map(item => item.count);
                trendsChart.data.datasets[1].data = data.data.jobTrends.map(item => item.count);
                trendsChart.update();
            }
        } catch (error) {
            console.error('加载趋势数据失败:', error);
        }
    }

    // 获取行业分布数据
    async function loadIndustryData() {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('http://localhost:3001/api/stats/industry', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) throw new Error('获取行业数据失败');

            const data = await response.json();
            if (data.success) {
                // 更新行业图表
                const industries = [...new Set([...data.data.jobIndustry.map(item => item.industry), ...data.data.companyIndustry.map(item => item.industry)])];
                industryChart.data.labels = industries;
                industryChart.data.datasets[0].data = industries.map(industry => {
                    const jobItem = data.data.jobIndustry.find(item => item.industry === industry);
                    return jobItem ? jobItem.count : 0;
                });
                industryChart.data.datasets[1].data = industries.map(industry => {
                    const companyItem = data.data.companyIndustry.find(item => item.industry === industry);
                    return companyItem ? companyItem.count : 0;
                });
                industryChart.update();
            }
        } catch (error) {
            console.error('加载行业数据失败:', error);
        }
    }

    // 获取薪资范围数据
    async function loadSalaryData() {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('http://localhost:3001/api/stats/salary', {
                method: 'GET',
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });

            if (!response.ok) throw new Error('获取薪资数据失败');

            const data = await response.json();
            if (data.success) {
                // 更新薪资图表
                salaryChart.data.labels = data.data.map(item => item.range);
                salaryChart.data.datasets[0].data = data.data.map(item => item.count);
                salaryChart.update();
            }
        } catch (error) {
            console.error('加载薪资数据失败:', error);
        }
    }

    // 显示加载状态
    function showLoading(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = '<div class="loading"><div class="spinner"></div><p>加载中...</p></div>';
        }
    }

    // 隐藏加载状态
    function hideLoading(elementId) {
        const element = document.getElementById(elementId);
        if (element) {
            element.innerHTML = '';
        }
    }

    // 初始化页面
    async function initPage() {
        // 移除登录检查，管理员直接访问

        // 显示加载状态
        showLoading('stats-container');

        // 初始化图表
        initCharts();

        try {
            // 加载数据
            const days = parseInt(dateRangeSelect.value) || 30;
            await Promise.all([
                loadSystemOverview(),
                loadTrendData(days),
                loadIndustryData(),
                loadSalaryData()
            ]);
        } catch (error) {
            console.error('页面初始化失败:', error);
            alert('数据加载失败，请刷新页面重试');
        } finally {
            // 隐藏加载状态
            hideLoading('stats-container');
        }

        // 添加日期范围变化事件监听
        dateRangeSelect.addEventListener('change', async function() {
            const days = parseInt(this.value) || 30;
            showLoading('trends-container');
            try {
                await loadTrendData(days);
            } catch (error) {
                console.error('更新趋势数据失败:', error);
                alert('更新趋势数据失败');
            } finally {
                hideLoading('trends-container');
            }
        });

        // 登出按钮事件
        logoutBtn.addEventListener('click', function() {
            localStorage.removeItem('token');
            window.location.href = 'index.html';
        });

        // 添加响应式调整
        window.addEventListener('resize', function() {
            if (trendsChart) trendsChart.resize();
            if (applicationStatusChart) applicationStatusChart.resize();
            if (industryChart) industryChart.resize();
            if (salaryChart) salaryChart.resize();
        });        ]);
    }

    // 事件监听
    dateRangeSelect.addEventListener('change', function() {
        const days = parseInt(this.value);
        loadTrendData(days);
    });

    logoutBtn.addEventListener('click', function(e) {
        e.preventDefault();
        localStorage.removeItem('token');
        window.location.href = 'login.html';
    });

    // 初始化页面
    initPage();
});